package com.hafu.dao;

import com.hafu.model.KuCun;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class KuCunDao {

    public ArrayList<KuCun> getKuCunList() {
        ArrayList<KuCun> list = new ArrayList<>();
        // 这里添加从数据库查询库存列表的代码
        return list;
    }

    public KuCun getKuCunBySpName(String spName, Connection conn) throws SQLException {
        KuCun kuCun = null;
        String sql = "SELECT * FROM kucun WHERE spname = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, spName);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                kuCun = new KuCun();
                kuCun.setId(rs.getInt("id"));
                kuCun.setSpname(rs.getString("spname"));
                kuCun.setNum(rs.getInt("num"));
            }
        }
        return kuCun;
    }

    public boolean addKuCun(KuCun kuCun, Connection conn) throws SQLException {
        String sql = "INSERT INTO kucun (spname, num) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, kuCun.getSpname());
            pstmt.setInt(2, kuCun.getNum());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        }
    }

    public boolean updateKuCun(KuCun kuCun, Connection conn) throws SQLException {
        String sql = "UPDATE kucun SET num = ? WHERE spname = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, kuCun.getNum());
            pstmt.setString(2, kuCun.getSpname());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        }
    }
}